package middleware

import (
	"gitee.com/war2001/NiuMaEasyGo/global"
	"github.com/gin-gonic/gin"
)

// Middleware 中间件管理器
type Middleware struct {
}

// New 创建中间件管理器实例
func New() *Middleware {
	return &Middleware{}
}

// PreflightHandler 处理CORS预检请求的中间件
func PreflightHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == "OPTIONS" {
			// 获取请求的Origin
			origin := c.Request.Header.Get("Origin")
			if origin == "" {
				// 如果没有Origin头，使用通配符
				origin = "*"
			}

			// 设置CORS头
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
			c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
			c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
			c.Writer.Header().Set("Access-Control-Max-Age", "86400") // 24小时

			// 返回204状态码
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

// RegisterMiddlewares 注册全局中间件
func RegisterMiddlewares(r *gin.Engine) {
	// 使用预检请求处理中间件
	r.Use(PreflightHandler())

	// 使用Logger中间件
	r.Use(gin.Logger())
	// 使用Recovery中间件
	r.Use(gin.Recovery())
	// 使用CORS中间件
	r.Use(CORS())
	// 使用XSS防护中间件
	if global.Config != nil && global.Config.Security.XSS.Enable {
		r.Use(XSSWithConfig(XSSConfig{
			Enable:      global.Config.Security.XSS.Enable,
			ExcludeURLs: global.Config.Security.XSS.ExcludeURLs,
			SkipPaths:   []string{"/api/v1/file/upload"},
		}))
	}
	// 使用CSRF保护中间件
	if global.Config != nil && global.Config.Security.CSRF.Enable {
		// 使用默认配置，确保登录接口被排除
		csrfConfig := DefaultCSRFConfig()
		// 添加配置文件中的排除URL
		if len(global.Config.Security.CSRF.ExcludeURLs) > 0 {
			csrfConfig.ExcludeURLs = append(csrfConfig.ExcludeURLs, global.Config.Security.CSRF.ExcludeURLs...)
		}
		// 使用其他配置项
		csrfConfig.HeaderName = global.Config.Security.CSRF.HeaderName
		csrfConfig.CookieName = global.Config.Security.CSRF.CookieName
		csrfConfig.CookieDomain = global.Config.Security.CSRF.CookieDomain
		csrfConfig.CookiePath = global.Config.Security.CSRF.CookiePath
		csrfConfig.CookieMaxAge = global.Config.Security.CSRF.CookieMaxAge
		csrfConfig.CookieHTTPOnly = global.Config.Security.CSRF.CookieHTTPOnly
		csrfConfig.CookieSecure = global.Config.Security.CSRF.CookieSecure

		r.Use(CSRFWithConfig(csrfConfig))
	}
}

// RegisterAuthMiddlewares 注册需要认证的API中间件
func RegisterAuthMiddlewares(r *gin.RouterGroup) {
	// 使用JWT认证中间件
	r.Use(JWTAuth())
}

// RegisterAPIMiddlewares 注册API中间件
func RegisterAPIMiddlewares(r *gin.RouterGroup) {
	// 注册API限流中间件
	r.Use(APIRateLimiter(20, 50, true))
}

// RegisterPublicMiddlewares 注册公共API中间件
func RegisterPublicMiddlewares(r *gin.RouterGroup) {
	// 公共API不需要认证
}

// RegisterLoginMiddlewares 注册登录API中间件
func RegisterLoginMiddlewares(r *gin.RouterGroup) {
	// 登录API不需要认证
}

// CORS 跨域中间件
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求的Origin
		origin := c.Request.Header.Get("Origin")
		if origin == "" {
			// 如果没有Origin头，使用通配符
			origin = "*"
		}

		// 设置CORS头
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")

		// 处理OPTIONS请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
